package org.zwy.gradetrack.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.OperationLog;
import org.zwy.gradetrack.entity.User;
import org.zwy.gradetrack.security.JwtTokenUtil;
import org.zwy.gradetrack.service.OperationLogService;
import org.zwy.gradetrack.service.UserService;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OperationLogService operationLogService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest request) {
        logger.info("用户尝试登录: {}", request.getUsername());
        
        try {
            // 获取用户信息
            User user = userService.lambdaQuery()
                    .eq(User::getUsername, request.getUsername())
                    .one();

            if (user == null) {
                logger.error("用户不存在: {}", request.getUsername());
                return Result.error(401, "用户名或密码错误");
            }

            logger.info("数据库中的密码: {}", user.getPassword());
            logger.info("输入的密码: {}", request.getPassword());
            
            // 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );
            
            // 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 生成JWT令牌
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String token = jwtTokenUtil.generateToken(userDetails);
            
            // 记录操作日志
            OperationLog log = new OperationLog();
            log.setUserId(user.getId());
            log.setOperationModule("用户认证");
            log.setOperationType("登录");
            log.setOperationDesc("用户登录");
            log.setOperationIp(request.getIp());
            operationLogService.createLog(log);
            
            // 返回用户信息和token
            Map<String, Object> result = new HashMap<>();
            result.put("token", "Bearer " + token);
            result.put("user", user);
            
            logger.info("用户登录成功: {}", request.getUsername());
            return Result.success(result);
        } catch (Exception e) {
            logger.error("登录失败: {}", e.getMessage(), e);
            return Result.error(401, "用户名或密码错误");
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        try {
            // 获取当前用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            User user = userService.getById(userDetails.getUsername());
            
            // 记录操作日志
            OperationLog log = new OperationLog();
            log.setUserId(user.getId());
            log.setOperationModule("用户认证");
            log.setOperationType("登出");
            log.setOperationDesc("用户登出");
            operationLogService.createLog(log);
            
            // 清除认证信息
            SecurityContextHolder.clearContext();
            
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "登出失败：" + e.getMessage());
        }
    }
    
    /**
     * 登录请求参数
     */
    public static class LoginRequest {
        private String username;
        private String password;
        private String ip;
        
        // Getters and Setters
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
        
        public String getIp() {
            return ip;
        }
        
        public void setIp(String ip) {
            this.ip = ip;
        }
    }
} 